<?php
/**
 * helper公共类
 */
class HelperModel {
	

	/**
	 * 设置前台用户登录session信息
	 * @param int $id member表会员ID
	 */
	function setLoginSession($id,$nickname=''){
		$result = DB('member')->field('id,username,nickname,type')->where("id={$id}")->find();
		if($nickname)
		    $result['nickname'] = $nickname;
        $_SESSION['member'] = $result;
	}
			

	/** 过滤掉非UTF-8字符
	 *   @param  String  $ostr
	 *   @return String
	 */
	function filter_utf8_char($text){
	    $clean_text = "";
	
	    // Match Emoticons
	    $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
	    $clean_text = preg_replace($regexEmoticons, '', $text);
	
	    // Match Miscellaneous Symbols and Pictographs
	    $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
	    $clean_text = preg_replace($regexSymbols, '', $clean_text);
	
	    // Match Transport And Map Symbols
	    $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
	    $clean_text = preg_replace($regexTransport, '', $clean_text);
	
	    // Match Miscellaneous Symbols
	    $regexMisc = '/[\x{2600}-\x{26FF}]/u';
	    $clean_text = preg_replace($regexMisc, '', $clean_text);
	
	    // Match Dingbats
	    $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
	    $clean_text = preg_replace($regexDingbats, '', $clean_text);
	    
	    // 过滤掉emoji表情
	    $clean_text = self::filterEmoji($clean_text);
	
	    return $clean_text;
	}
	
	
	// 过滤掉emoji表情
	function filterEmoji($str)
	{
	    $str = preg_replace_callback(
	        '/./u',
	        function (array $match) {
	            return strlen($match[0]) >= 4 ? '' : $match[0];
	        },
	        $str);
	
	    return $str;
	}
	
	
	/**
	 * 发送短信/语音验证码
	 * @param string $code 验证码
	 * @param string $mobile 手机
	 * @param string $title 标题
	 * @param int $tempId 短信模板id（可为空，为空时发语音验证码）
	 */
	private function sendSmsVerifyCode($code,$mobile,$title,$tempId=''){
	    //检查发送频率是否过高
	    $duration = (int)My::alias2field('config','system_config','params.sms_duration');//发送频率（限制次数的时长）（整数，单位为分钟，0为无限制）
	    $number = (int)My::alias2field('config','system_config','params.sms_number');//发送频率（限制次数）（整数，0为无限制）
	    $prompt = My::alias2field('config','system_config','params.sms_prompt');//超限错误提示
	    if(My::is_id($duration) and My::is_id($number)){
	        $start_time = date("Y-m-d H:i:s", strtotime("-{$duration} minute"));
	        if(DB('sms_log')->where("tel='{$mobile}' AND `adddate`>='{$start_time}'")->cache()->count()>=$number){
	            if($prompt)
	                My::ajaxReturn(300,$prompt);
	                else
	                    My::ajaxReturn(300,'已超'.$number.'次短信请求，请'.$duration.'分钟后再试！');
	        }
	    }
	    require_once (COM_DIR."Sms/yuntongxun/Yuntongxun.class.php");
	    //模板ID不为空时发短信验证码
	    if($tempId){
	        $result = Yuntongxun::getInstance()->sendSMS($mobile,array($title,$code,10),$tempId);
	    }
	    //模板ID为空时发语音验证码
	    else{
	        $result = Yuntongxun::getInstance()->sendVoice($mobile,$code);
	    }
	    if($result){
	        $_SESSION['sms_code'] = $code;
	        $_SESSION['mobile'] = $mobile;
	        $_SESSION['sms_code_until'] = date("Y-m-d H:i:s", strtotime("+600 second"));//验证码有效时间10分钟
	        if(My::is_id(C('sms_config.number')) and My::is_id(C('sms_config.duration'))){
	            DB('sms_log')->clear()->add(array('tel'=>$mobile,'adddate'=>date("Y-m-d H:i:s")));
	        }
	        My::ajaxReturn(200,$tempId ? '短信验证码已发出，请注意查看手机短信!' : '语音验证码已发出，请注意接听电话!');
	    }else{
	        My::ajaxReturn(300,'短信验证码发送失败!');
	    }
	}
	
	
	/**
	 * 发送短信/邮箱验证码
	 * @param string $mobile 手机/邮箱
	 * @param string $title 标题
	 */
	public function sendVerifyCode($mobile,$title,$tempId=''){
	    if($mobile=='')
	        My::ajaxReturn(300,'手机/邮箱不能为空');
        //产生随机验证码
        $randStr = str_shuffle('1234567890');
        $code = substr($randStr,0,6);
        //手机号
        if(My::is_tel($mobile)){
            self::sendSmsVerifyCode($code,$mobile,$title,$tempId);
        }elseif(My::is_email($mobile)){
            $emailParam['title'] = "{$title}验证码";
            $emailParam['content'] = "您的{$title}验证码为{$code}，请在10分钟内正确输入。";
            //收件人
            $emailParam['receiver'][] = $mobile;
            $emailParam['host'] = C('email_smtp');
            $sendok = My::sendApiMail($emailParam);
            if($sendok==true){
                $_SESSION['sms_code'] = $code;
                $_SESSION['mobile'] = $mobile;
                $_SESSION['sms_code_until'] = date("Y-m-d H:i:s", strtotime("+600 second"));//验证码有效时间10分钟
                My::ajaxReturn(200,'验证码已发出，请注意查看邮箱!');
            }else
                My::ajaxReturn(200,'验证码发送失败!');
        }else{
            My::ajaxReturn(300,'手机/邮箱无效');
        }
	}
}